package com.shenmazong.recv.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: 1、发送端进行错误消息回调 2、队列和交换机持久化（默认就是持久化） 3、接收消息进行手动确认
 * @date 2022/2/8 15:44
 */

@Component
@Slf4j
public class RecvMessage {

    @Autowired
    RedisTemplate redisTemplate;

    @RabbitListener(queues = "hello")
    public void onHelloMessage(Message message, Channel channel) {
        String msg = null;
        try {
            // 获取消息的唯一标识
            String msgId = message.getMessageProperties().getMessageId();

            // 判断是否已被消费
            if(!redisTemplate.hasKey(msgId)) {
                // 处理消息
                String s = new String(message.getBody());
                log.info("onHelloMessage:"+s);

                // 设置已经消费的标识
                redisTemplate.opsForValue().set(msgId, msgId, 5, TimeUnit.MINUTES);
            }

            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
